const Koa = require("koa");
const app = new Koa();
const render = require('koa-art-template')
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const path = require("path");
const static = require('koa-static');
const Sequelize = require('sequelize');
const config = require('./config/mysql');
const koaBody = require('koa-body');
const fs = require('fs');
const openbrw = require('./adLogin');
const { log, getLog } = require("./middleware/log");
app.use(koaBody({
  multipart: true, // 支持文件上传
  formLimit: '10mb',
  formidable: {
    uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录
    keepExtensions: true,    // 保持文件的后缀
    maxFieldsSize: 1000 * 1024 * 1024, // 文件上传大小
    onFileBegin: (name, file) => { // 文件上传前的设置
      // console.log(`name: ${name}`);
      // console.log(file);
    },
  }
}))
// $ npm install --save pg pg-hstore # Postgres
// $ npm install --save mysql2
// $ npm install --save mariadb
// $ npm install --save sqlite3
// $ npm install --save tedious # Microsoft SQL Server
var sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    idle: 30000
  }
});
sequelize
  .authenticate()
  .then(() => {
    console.log('数据库连接成功');
  })
  .catch(err => {
    console.error('数据库连接失败', err);
  });
// const mysql = require('mysql');
// const connection = mysql.createConnection({
//     host     : '10.0.0.189',
//     user     : 'root',
//     password : 'fanjiantao',
//     database : 'nodeDB',
//     port: '3306',
//   });
// connection.connect(function(err) {
//     if (err) {
//       console.error('error connecting: ' + err.stack);
//       return;
//     }
//     console.log('connected as id ' + connection.threadId);
// });
const User = sequelize.define('users', {
  // 属性
  userName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  password: {
    type: Sequelize.STRING
    // allowNull 默认为 true
  },
  headImg: {
    type: Sequelize.STRING
  }
}, {
  timestamps: false
  // 参数
});
app.use(static(path.join(__dirname + "/static")));
render(app, {
  root: path.join(__dirname, 'view'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
});
router.get('/', async function (ctx, next) {
  await User.findAll().then(users => {
    ctx.render('index', { users: users, title: "koa" });
  });
})
router.post('/formData', async function (ctx, next) {
  var data = ctx.request.body;
  await User.create({ userName: data.name, password: ctx.request.body.password }).then(users => {
    ctx.body = 'ok';
    ctx.response.redirect('/');
    // ctx.render('index', { users: users, title: "koa" });
  });
})

router.get('/log', async function (ctx, next) {
  console.log("请求log页面")
  ctx.render('log', { logs: getLog() });
  await next();
})

router.get('/logs', async function (ctx, next) {
  await next();
})

router.post('/test', async function (ctx, next) {
  ctx.body = ctx.request.header;
  await next();
})

router.get('/createAd', async function (ctx, next) {
  // ctx.body="正在执行脚本";
  openbrw.open();
  ctx.response.redirect('/log');
})
router.get('/delete', async function (ctx, next) {
  await User.destroy({
    where: {
      id: ctx.request.query.id
    }
  })
  ctx.response.redirect('/');

})
router.post('/uploadImg', async function (ctx, next) {
  const file = ctx.request.files.file;
  const fileName = ctx.request.body.name
  // console.log(file)
  // console.log(__dirname)
  const reader = fs.createReadStream(file.path); // 创建可读流
  // const ext = file.name.split('.').pop(); // 获取上传文件扩展名
  const upStream = fs.createWriteStream(__dirname + "\/static\/img\/" + fileName); // 创建可写流
  // rs.on('data', function (data) {
  //   console.log(data.toString());
  // })
  await reader.pipe(upStream); // 可读流通过管道写入可写流
  ctx.body = { code: 0, data: { url: ctx.header.origin + "/img/" + fileName }, message: '上传成功' }
})
app.use(bodyParser());
app.use(router.routes());
app.use(log({}, router));
app.listen(3000);
function getIPAdress(){
  var interfaces = require('os').networkInterfaces();
  for(var devName in interfaces){
      var iface = interfaces[devName];
      for(var i=0;i<iface.length;i++){
          var alias = iface[i];
          if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
              return alias.address;
          }
      }
  }
}

console.log('server runing.....',"http://"+getIPAdress()+":3000")